import {getLoginUser} from "../../service/user";
import {goPay, prepareCacheOrder} from "../../service/order";
import {simpleGet} from "../../utils/request";
import {showToast} from "../../utils/tool";

const app = getApp()
const global = app.globalData

Page({
    data: {
        nav:{
            height:false,
            color:"#fff",
        },
        options:{},
        imageUrl: global.imageUrl,
        info:null,
        user:null,
    },
    onLoad: function (options = {}) {
        this.init(options)
    },

    numChange(e){
        const {value} = e.detail
        const {info} = this.data
        let num = parseInt(value)

        if (info.once_buy_num != -1 && num > info.once_buy_num){
            num = info.once_buy_num
            showToast(`每次限购${info.once_buy_num}件`);
        }

        if (info.total_num != -1 && num > info.total_num){
            num = info.total_num
            showToast(`仅剩${info.total_num}件`);
        }

        this.setData({
            [`info.num`]: num,
            [`info.total`]: (info.active_price * num).toFixed(2)    // 防止出现多位小数，这里必须转为2位
        })
    },

    buyClick(){
        const {info} = this.data
        goPay({
            goodsUl:[info],
            order_type:'seckill',
        })
    },


    /**
     * 图片预览
     */
    imagePreview: function (e) {
        let {images,index} = e.target.dataset
        this.setData({
            'imgPreview.images': images,
            'imgPreview.show': true,
            'imgPreview.index': index,
        })

    },

    async init(options){
        options = options||{}
        const info = await simpleGet("/detail/seckill", {id:options.id})
        const user = await getLoginUser()
        // 添加默认的商品数量
        if (info) {
            info.num = 1
            info.total = info.active_price  * 1
        }

        this.setData({
            info,
            user
        })
    }
});
